from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from django.shortcuts import render, redirect
from django.utils.safestring import mark_safe
from app01 import models
from app01.models import UserInfo,PrettyNum,Department
from app01.utils.pagination import Pagination


# Create your views here.
def depart_list(request):
    """部门列表"""
    #去数据库中获取所有的部门列表
    queryset = models.Department.objects.all()   #获取所有的部门列表的信息  得到的是一个列表

    page_object = Pagination(request, queryset, page_size=2)

    context = {
        "queryset": page_object.page_queryset,
        "page_string": page_object.html(),

    }

    return render(request,'depart_list.html',context)

def depart_add(request):
    """添加部门"""
    if request.method == "GET":
        return render(request, 'depart_add.html')

    # 获取用户通过POST方式提交过来的数据(tittle输入为空暂时不考虑)

    title = request.POST.get("title")

    #保存到数据库
    models.Department.objects.create(title=title)
    #重定向回列表页面
    return redirect("/depart/list/")

def depart_delete(request):
    """删除部门"""
    nid = request.GET.get("nid")
    models.Department.objects.filter(id=nid).delete()
    return redirect("/depart/list/")

def depart_edit(request,nid):

    if request.method == "GET":

        row_object = models.Department.objects.filter(id=nid).first()

        return render(request,'depart_edit.html',{"row_object":row_object})


    #根据ID找到数据库中的数据进行更新

    models.Department.objects.filter(id=nid).update(title=request.POST.get("title"))

    return redirect("/depart/list/")

def user_list(request):
    """部门列表"""
    #去数据库中获取所有的部门列表
    queryset = models.UserInfo.objects.all()   #获取所有的部门列表的信息  得到的是一个列表

    page_object = Pagination(request,queryset,page_size=2)
    context = {
        "queryset": page_object.page_queryset,
        "page_string": page_object.html(),

    }
    return render(request,'user_list.html',context)

def user_add(request):
    """添加用户"""


    if request.method == "GET":
        context = {
            'gender_choices': models.UserInfo.gender_choices,
            "depart_list": models.Department.objects.all()
        }
        return render(request, 'user_add.html', context)

        # 获取用户提交的数据
    user = request.POST.get('user')
    pwd = request.POST.get('pwd')
    age = request.POST.get('age')
    account = request.POST.get('ac')
    ctime = request.POST.get('ctime')
    gender = request.POST.get('gd')
    depart_id = request.POST.get('dp')

        # 添加到数据库中
    models.UserInfo.objects.create(name=user, password=pwd, age=age,
                                       account=account, create_time=ctime,
                                       gender=gender, depart_id=depart_id)

        # 返回到用户列表页面
    return redirect("/user/list/")

from django import forms

class UserModelForm(forms.ModelForm):
    name = forms.CharField(min_length=3, label="用户名")   #重写字段校验规则


    class Meta:        # 重新定义字段的目的是此处不想把所有字段全部拿过来  固定格式
        model = models.UserInfo
        fields = ['name', 'password', 'age', 'account', 'create_time', 'gender', 'depart',]
        # widgets = {
        #     "name": forms.TextInput(attrs={'class': 'form-control'}),
        #     "password": forms.TextInput(attrs={'class': 'form-control'}),
        #     "age": forms.TextInput(attrs={'class': 'form-control'}),
        #     "account": forms.TextInput(attrs={'class': 'form-control'}),
        #     "create_time": forms.TextInput(attrs={'class': 'form-control'}),
        #     "gender": forms.TextInput(attrs={'class': 'form-control'}),
        #     "depart": forms.TextInput(attrs={'class': 'form-control'}),
        # }#重新定义一个插件 把各个输入框的样式定义进去
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
            # 循环找到所有的插件，添加了class="form-control"
        for name, field in self.fields.items():
                # if name == "password":
                #     continue
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}


def user_model_form_add(request):
    if request.method == "GET":
        form = UserModelForm()    #实列化

        return  render(request,'user_model_form_add.html',{"form":form})
    #用户通过。post提交数据
    # 用户POST提交数据，数据校验。
    form = UserModelForm(data=request.POST)
    if form.is_valid():
        # 如果数据合法，保存到数据库
        # {'name': '123', 'password': '123', 'age': 11, 'account': Decimal('0'), 'create_time': datetime.datetime(2011, 11, 11, 0, 0, tzinfo=<UTC>), 'gender': 1, 'depart': <Department: IT运维部门>}
        # print(form.cleaned_data)
        # models.UserInfo.objects.create(..)
        form.save()
        return redirect('/user/list/')

    # 校验失败（在页面上显示错误信息）
    return render(request, 'user_model_form_add.html', {"form": form})


def user_edit(request,nid):
    row_object = models.UserInfo.objects.filter(id=nid).first()
    if request.method == "GET":

        '''编辑用户'''
        #根据id去数据库获取那一行数据。下面这两行用于携带默认值回到编辑页面


        form = UserModelForm(instance=row_object)

        return render(request,'user_edit.html', {'form': form})



    form = UserModelForm(data=request.POST,instance=row_object)  #将数据更新到这一行
    if form.is_valid():
    # 如果数据合法，保存到数据库
    # {'name': '123', 'password': '123', 'age': 11, 'account': Decimal('0'), 'create_time': datetime.datetime(2011, 11, 11, 0, 0, tzinfo=<UTC>), 'gender': 1, 'depart': <Department: IT运维部门>}
    # print(form.cleaned_data)
    # models.UserInfo.objects.create(..)
        form.save()
        return redirect('/user/list/')
    return render(request, 'user_edit.html', {"form": form})

def user_delete(request):
    """删除部门"""
    nid = request.GET.get("nid")
    models.UserInfo.objects.filter(id=nid).delete()
    return redirect("/user/list/")




class PrettyModelForm(forms.ModelForm):
    # 自定义：验证方式一

    # mobile = forms.CharField(
    #     label="手机号",
    #     #validators=[RegexValidator(r'^159[0-9]+$','数字必须以159开头')],
    #     validators=[RegexValidator(r'^1\d{10}$','手机号格式不对')],
    # ),
    # name = forms.CharField(min_length=3, label="用户名")   #重写字段校验规则




    class Meta:        # 重新定义字段的目的是此处不想把所有字段全部拿过来  固定格式
        model = models.PrettyNum
        #fields = ['mobile', 'price', 'level', 'status',]
        fields = "__all__"
     #   exclude = ['level']

        # widgets = {
        #     "name": forms.TextInput(attrs={'class': 'form-control'}),
        #     "password": forms.TextInput(attrs={'class': 'form-control'}),
        #     "age": forms.TextInput(attrs={'class': 'form-control'}),
        #     "account": forms.TextInput(attrs={'class': 'form-control'}),
        #     "create_time": forms.TextInput(attrs={'class': 'form-control'}),
        #     "gender": forms.TextInput(attrs={'class': 'form-control'}),
        #     "depart": forms.TextInput(attrs={'class': 'form-control'}),

    # 利用钩子方法实现 验证方式二
    def clean_mobile(self):
        text_mobile = self.cleaned_data["mobile"]   #获取用户传入的数据
        if len(text_mobile) != 11:
            raise ValidationError("格式错误")

        exists = models.PrettyNum.objects.filter(mobile=text_mobile).exists()
        if exists:
            raise ValidationError("手机号已经存在")
        return text_mobile




        # }#重新定义一个插件 把各个输入框的样式定义进去
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
            # 循环找到所有的插件，添加了class="form-control"
        for name, field in self.fields.items():
                # if name == "password":
                #     continue
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}
def prettynum_list(request):



    # 给列表里加300条数据
    # for i in range(300):
    #     models.PrettyNum.objects.create(mobile="18188888888",price=10,level=1,status=1)

    data_dict = {}
    search_data = request.GET.get('q', "")
    if search_data:
        data_dict["mobile__contains"] = search_data

    queryset = models.PrettyNum.objects.filter(**data_dict).order_by("-level")

    page_object = Pagination(request, queryset)

    context = {
        "search_data": search_data,

        "queryset": page_object.page_queryset,  # 分完页的数据
        "page_string": page_object.html()  # 页码
    }
    return render(request, 'prettynum_list.html', context)

def prettynum_model_form_add(request):
    if request.method == "GET":
        form = PrettyModelForm()    #实列化

        return  render(request,'prettynum_model_form_add.html',{"form":form})

    form = PrettyModelForm(data=request.POST)
    if form.is_valid():
        # 如果数据合法，保存到数据库
        # {'name': '123', 'password': '123', 'age': 11, 'account': Decimal('0'), 'create_time': datetime.datetime(2011, 11, 11, 0, 0, tzinfo=<UTC>), 'gender': 1, 'depart': <Department: IT运维部门>}
        # print(form.cleaned_data)
        # models.UserInfo.objects.create(..)
        form.save()
        return redirect('/prettynum/list/')

    # 校验失败（在页面上显示错误信息）
    return render(request, 'prettynum_model_form_add.html', {"form": form})


class PrettyEditModelForm(forms.ModelForm):

    mobile = forms.CharField(disabled=True, label='手机号'),
    class Meta:
        model = models.PrettyNum
        fields = ['mobile', 'price','level', 'status',]

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            field.widget.attrs = {"class": "form-control", "placeholder": field.label}

    def clean_mobile(self):
        # 当前编辑那一行的ID


        text_mobile = self.cleaned_data["mobile"]   #获取用户传入的数据    除自己以外如果还有相同的手机号！！！！！重要重要校验
        exists = models.PrettyNum.objects.exclude(id=self.instance.pk).filter(mobile=text_mobile).exists()
        if exists:
            raise ValidationError("手机号已经存在")
        return text_mobile

def prettynum_edit(request,nid):
    row_object = models.PrettyNum.objects.filter(id=nid).first()

    if request.method == "GET":
        '''编辑用户'''
        form = PrettyEditModelForm(instance=row_object)

        return render(request, 'prettynum_edit.html', {'form': form})

    form = PrettyEditModelForm(data=request.POST, instance=row_object)  # 将数据更新到这一行
    if form.is_valid():

        form.save()
        return redirect('/prettynum/list/')
    return render(request, 'prettynum_edit.html', {"form": form})


def prettynum_delete(request):
    nid = request.GET.get("nid")
    models.PrettyNum.objects.filter(id=nid).delete()
    return redirect("/prettynum/list/")












